package com.example.ricebibackend.common.utils;

import com.example.ricebibackend.common.exception.GlobalException;
import jakarta.annotation.Resource;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

/**
 * 限流工具类
 * @author ricejson
 */
@Component
public class RateLimiterUtil {

    @Resource
    private RedissonClient redissonClient;

    public void doRateLimit(String key) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        // 设置限流速率(每秒3次)
        rateLimiter.trySetRate(RateType.OVERALL, 3, 1, RateIntervalUnit.SECONDS);
        // 每次申请一个令牌
        boolean canOps = rateLimiter.tryAcquire(1);
        if (!canOps) {
            // 不能进行操作
            throw new GlobalException(500, "限流器生效!无法操作");
        }
    }
}
